import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义 Store
export const useUserStore = defineStore(
  'user',
  () => {
    // 用户信息
    const token = ref<any>()
    const userInfo = ref<any>()
    const loginStatus = ref<boolean>(false)
    const channelStatus = ref<boolean>(true)

    // 保存渠道来源悬浮球小红点展示状态
    const setChannelStatus = (val: any) => {
      channelStatus.value = val
    }

    // 保存暂不登录状态
    const setLoginStatus = (val: any) => {
      loginStatus.value = val
    }

    // 保存token，登录时使用
    const setToken = (val: any) => {
      token.value = val
    }

    // 清理token，退出时使用
    const clearToken = () => {
      token.value = undefined
    }

    // 保存用户信息，登录时使用
    const setUserInfo = (val: any) => {
      userInfo.value = val
    }

    // 清理用户信息，退出时使用
    const clearUserInfo = () => {
      userInfo.value = undefined
    }

    return {
      userInfo,
      token,
      loginStatus,
      channelStatus,
      setToken,
      clearToken,
      setUserInfo,
      clearUserInfo,
      setLoginStatus,
      setChannelStatus,
    }
  },
  // TODO: 持久化
  {
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
